package ro.ubbcluj.cs.damate.persistence.entities;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import java.util.List;

import static javax.persistence.CascadeType.*;
import static javax.persistence.FetchType.LAZY;
import static javax.persistence.GenerationType.*;

/**
 * @author Lóránd Fazakas (lorand)
 *         Date: 4/22/12
 *         Time: 1:12 AM
 */
@Table(name = "user_group", catalog = "damate")
@Entity
public class Group {

    private Long groupId;

    @Column(name = "groupId", nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
    @Id
    @GeneratedValue(strategy= IDENTITY)
    public Long getGroupId() {
        return groupId;
    }

    public void setGroupId(Long groupId) {
        this.groupId = groupId;
    }

    private String groupName;

    @Column(name = "groupName", nullable = false, insertable = true, updatable = true, length = 60, precision = 0)
    @Basic
    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    private List<Role> roles;

    @ManyToMany(fetch = LAZY, cascade = REFRESH)
    @OrderBy("roleName asc")
    @JoinTable(name = "group_has_role",
               joinColumns = { @JoinColumn(name = "group_groupId")},
               inverseJoinColumns={@JoinColumn(name="role_roleId")})
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    private List<User> groupMembers;

    @OneToMany(fetch = LAZY, cascade = ALL, mappedBy = "group")
    @OrderBy("firstname, lastname asc")
    public List<User> getGroupMembers() {
        return groupMembers;
    }

    public void setGroupMembers(List<User> groupMembers) {
        this.groupMembers = groupMembers;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Group that = (Group) o;

        if (groupId != that.groupId) return false;
        if (groupName != null ? !groupName.equals(that.groupName) : that.groupName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = groupId.intValue();
        result = 31 * result + (groupName != null ? groupName.hashCode() : 0);
        return result;
    }
}
